package com.biostime.dingdingbox.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.dingdingbox.common.config.Global;
import com.biostime.dingdingbox.common.persistence.Page;
import com.biostime.dingdingbox.common.utils.StringUtils;
import com.biostime.dingdingbox.common.web.BaseController;
import com.biostime.dingdingbox.modules.sys.entity.Dict;
import com.biostime.dingdingbox.modules.sys.entity.Menu;
import com.biostime.dingdingbox.modules.sys.entity.Role;
import com.biostime.dingdingbox.modules.sys.entity.RolePermissions;
import com.biostime.dingdingbox.modules.sys.service.MenuService;
import com.biostime.dingdingbox.modules.sys.service.RolePermissionsService;
import com.biostime.dingdingbox.modules.sys.service.RoleService;
import com.biostime.dingdingbox.modules.sys.utils.DictUtils;
import com.google.common.collect.Maps;

/**
 * 角色表Controller
 * @author phil
 * @version 2015-11-08
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/role")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private RolePermissionsService rolePermissionsService;
	
	@ModelAttribute
	public Role get(@RequestParam(required=false) String id) {
		Role entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = roleService.get(id);
		}
		if (entity == null){
			entity = new Role();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = {"list", ""})
	public String list(Role role, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Role> page = roleService.findPage(new Page<Role>(request, response), role); 
		model.addAttribute("page", page);
		return "modules/sys/roleList";
	}

	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = "form")
	public String form(Role role, Model model) {
		
		List<Dict> permDicts = DictUtils.getDictList("permission");
		
		Map<String,String> permMap = Maps.newHashMap();
		for(Dict dict : permDicts){
			if(!permMap.containsKey(dict.getValue())){
				permMap.put(dict.getValue(),dict.getLabel());
			}
		}
		
		/**获取所有权限**/
		RolePermissions exm = new RolePermissions();
		exm.setRoleId(StringUtils.toInteger(role.getId()));
		List<RolePermissions> rolePerms = rolePermissionsService.findList(exm);
		Map<String,String> rolePermMap = Maps.newHashMap();
		for(RolePermissions rp : rolePerms){
			String key = String.format("%s:%s", rp.getNavId(),rp.getPermissions());
			if(!rolePermMap.containsKey(key)){
				rolePermMap.put(key, "1");
			}
		}
		
		List<Menu> menuList = menuService.getAllMenu();
		for(Menu menu : menuList){
			if(menu.getPermission()!=null){
				String[] permissions = menu.getPermission().split(",");
				
				if(permissions!=null && permissions.length>0){
					for(String pKey:permissions){
						RolePermissions perm = new RolePermissions();
						perm.setNavId(menu.getNavId());
						perm.setRoleId(StringUtils.toInteger(role.getId()));
						perm.setPermName(permMap.get(pKey));
						perm.setPermissions(pKey);
						perm.setChecked(rolePermMap.containsKey(String.format("%s:%s", menu.getNavId(),pKey)));
						menu.getPermissions().add(perm);
					}
				}
			}
		}
		
		model.addAttribute("role", role);
		model.addAttribute("menuList", menuList);
		
		return "modules/sys/roleForm";
	}

	@RequiresPermissions(value={"sys:role:edit","sys:role:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Role role, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, role)){
			return form(role, model);
		}
		
		try{
			roleService.save(role,request);
		}catch(Exception ex){
			ex.printStackTrace();
			
			logger.error("角色["+role.getId()+"]保存异常:",ex);
			
			model.addAttribute("message", ex.getMessage());
			return form(role, model);
		}
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/sys/role/?repage";
	}
	
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Role role, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				/**删掉所有权限**/
				RolePermissions exm = new RolePermissions();
				exm.setRoleId(StringUtils.toInteger(id));;
				rolePermissionsService.deleteAll(exm);
				
				roleService.delete(new Role(id));
			}
		}else{
			/**删掉所有权限**/
			RolePermissions exm = new RolePermissions();
			exm.setRoleId(StringUtils.toInteger(role.getId()));;
			rolePermissionsService.deleteAll(exm);
			
			roleService.delete(role);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/sys/role/?repage";
	}

}